<?php
!defined('M_VIEW_DIR')&&define('M_VIEW_DIR',M_DIR.'view/');

class lib_tpl extends lib_milkphp_library{
	//基础路径
	var $_style='default';
	
	static function _do($name=null){
		static $instance = NULL;
		if(is_null($instance))
			$instance = new lib_tpl();
		return $instance->tplFile($name);
	}
	
	private function __construct(){
		if(empty(m()->style))m()->style='default';
	}
	
	function tplFile($basename,$extension='php'){
		if(empty($basename)){
			return $this;
		}
		if(!preg_match("/^[a-z|0-9|A-Z|_]+$/",$basename)||!preg_match("/^[a-z|0-9|A-Z|_]+$/",$extension)){
			milkphp()->debug('e','模版文件名不合法');
			return;
		}
		if(!@include_once(m()->dir['tpl'].m()->style.'/functions.php')){
			@include_once(m()->dir['tpl'].'default/functions.php');
		}
		if(is_file(m()->dir['tpl'].m()->style.'/'.$basename.'.'.$extension)){
			return m()->dir['tpl'].m()->style.'/'.$basename.'.'.$extension;
		}elseif(is_file(m()->dir['tpl'].'default/'.$basename.'.'.$extension)){
			return m()->dir['tpl'].'default/'.$basename.'.'.$extension;
		}else{
			milkphp()->debug('e','模版文件'.m()->tplDir.m()->style.'/'.$basename.'.'.$extension.'不存在');
		}
	}
	/**
	 * 返回网站当前Uri
	 * @return string
	 */
	function siteUri(){
		$sitefolder=explode('.php', $_SERVER['PHP_SELF']);
		return dirname($sitefolder[0]).'/';
	}
	
	function styleDir(){
		return m()->dir['tpl'].m()->style.'/';
	}
	
	/**
	 * 模块化模版
	 */
	function block($basename,$args=array()){
		if(!preg_match("/^[a-z|0-9|A-Z|_]+$/",$basename)){
			milkphp()->debug('e','模版文件名不合法');
			return;
		}
		$file =m()->dir['tpl'].m()->style.'/_block/'.$basename.'.php';
		if(!is_file($file)){
			$file =m()->dir['tpl'].'default/_block/'.$basename.'.php'; 
		}
		if(@include($file)){
			$blockName = 'block_'.ucwords($basename);
			if(method_exists($blockName,'_do')){
				return call_user_func_array(array($blockName,"_do"),array($args));
			}
			return new $blockName($args);
		}else{
			milkphp()->debug('e','模版文件'.$file.'不存在');
		}
	}
}